package cn.fz.learn02.controller.socket;

import cn.hutool.core.date.DateTime;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * springboot整合websocket，先引入websocket相关的工具包，和SSE相比额外的开发成本
 * <dependency>
 *  <groupId>org.springframework.boot</groupId>
 *  <artifactId>spring-boot-starter-websocket</artifactId>
 * </dependency>
 * 服务端使用@ServerEndpoint注解标注当前类为一个websocket服务器，客户端可以通过ws://localhost:8096/websocket/10086来连接到WebSocket服务器端,
 * // 接口路径 ws://localhost:8096/webSocket/userId;
 */
@Component
@Slf4j
@ServerEndpoint("/websocket/{userId}")
public class WebSocketServer {
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    private static final CopyOnWriteArraySet<WebSocketServer> webSockets = new CopyOnWriteArraySet<>();

    // 用来存在线连接数
    private static final Map<String, Session> sessionPool = new HashMap<String, Session>();

    // 链接成功调用的方法
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId) {
        try {
            this.session = session;
            webSockets.add(this);
            sessionPool.put(userId, session);
            log.info("【websocket服务端】有新的连接，总数为: {}", webSockets.size());
        } catch (Exception e) {
            // throw new RuntimeException(e);
        }
    }

    // 链接关闭调用的方法
    @OnClose
    public void onClose() {
        try {
            webSockets.remove(this);
            log.info("【websocket服务端】连接断开，总数为: {}" , webSockets.size());
        }catch (Exception e){
            log.error("【websocket服务端】连接断开 发生错误: {}",e.getMessage());
        }
    }

    // 收到客户端消息后调用的方法
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("【websocket服务端】收到客户端消息: {}", message);
        log.info("【websocket服务端】收到客户端对象: {}", session);
        Map<String,Object> result = new HashMap<>();
        result.put("code", HttpStatus.HTTP_OK);
        result.put("receive_message",message);
        result.put("send_message","收到你的消息了："+message);
        result.put("date", DateTime.now().toString());
        JSONObject obj = new JSONObject(result);
        session.getAsyncRemote().sendText(obj.toString());
    }

    // 发送错误时的处理
    @OnError
    public void onError(Session session, Throwable e) {
        log.error("【websocket服务端】发生错误: {}",e.getMessage());
        // e.printStackTrace();
    }

    // 此为广播消息
    public void sendAllMessage(String message){
        log.info("【websocket服务端】广播消息: {}" , message);
        for (WebSocketServer webSocket : webSockets) {
            try {
                if (webSocket.session.isOpen()) {
                    webSocket.session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息
    public void sendOneMessage(String userId, String message) {
        Session session1 = sessionPool.get(userId);
        if (session1 != null && session1.isOpen()){
            log.info("【websocket服务端】 单点消息: {}", message);
            try {
                session1.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                log.error("发送单点消息失败：{}",e.getMessage());
                // throw new RuntimeException(e);
            }
        }
    }

    /**
     * 此为单点消息(多人)
     */
    public void sendMoreMessage(String[] userIds, String message) {
        for (String userId : userIds) {
            Session session = sessionPool.get(userId);
            if (session != null && session.isOpen()) {
                try {
                    log.info("【websocket服务端】 单点消息(多人): {}", message);
                    session.getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    log.error("发送单点消息(多人)失败：{}",e.getMessage());
                    // e.printStackTrace();
                }
            }
        }
    }
}
